"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 性能看护
Case Name   : drawAndEmail
Create At   : 2021/02/04
Owner       : z00562814
Description :
    1.格式化近七日tpmC日志文件
    2.绘制波形图
    3.发送邮件
Expect      :
History     :
"""

import email.mime.image
import email.mime.multipart
import email.mime.text
import email.utils

from email.header import Header

import numpy as np
import matplotlib.pyplot as plt


SUBJECT = '邮件主题'
SENDER = ['发送人邮箱']
RECEIVER = ['接收人邮箱']
CCTO = ['抄送人邮箱']
DOMAIN_NAME = '域账号'
DOMAIN_PWD = '域密码'
SMTP_SERVER = '邮箱服务器'
LOG_PATH = '脚本路径/2P_ARM_email.log'
LOG_GS_VERSION = '脚本路径/2P_gs_version.log'
PNG_PATH = '脚本路径/tpmc.png'
XML_FILE_FORMAT = 'xmlformat.xml'
XML_FILE = 'xmlformat1.xml'
PNG_FILE = 'tpmc.png'



class Mail(object):

    def __init__(self):
        self.s = ''

    @staticmethod
    def __format_addr__(addr):
        alias_name, addr = email.utils.parseaddr(addr)
        return email.utils.formataddr((Header(alias_name, charset="utf-8")
                                       .encode(), addr))

    def graph(self):
        '''
        :return: 绘制
        '''
        x = [0,
             (datetime.datetime.now() + datetime.timedelta(days=-6)).strftime(
                 "%m-%d"),
             (datetime.datetime.now() + datetime.timedelta(days=-5)).strftime(
                 "%m-%d"),
             (datetime.datetime.now() + datetime.timedelta(days=-4)).strftime(
                 "%m-%d"),
             (datetime.datetime.now() + datetime.timedelta(days=-3)).strftime(
                 "%m-%d"),
             (datetime.datetime.now() + datetime.timedelta(days=-2)).strftime(
                 "%m-%d"),
             (datetime.datetime.now() + datetime.timedelta(days=-1)).strftime(
                 "%m-%d"),
             datetime.datetime.now().strftime("%m-%d")]

        data = np.loadtxt(LOG_PATH)
        plt.plot(data[:, 0], data[:, 3], c='g', marker='s', label=r'2P')
        plt.legend(loc='upper right')
        plt.xlabel('date/(day)')
        plt.ylabel('Tpmc/(tpmC)')
        plt.xticks(range(8), x)
        plt.ylim((0, 1700000))
        plt.grid(linestyle='-.')
        plt.axhline(y=1500000, c="r", ls="--", lw=2)
        plt.title('ARM+openEuler tpmc')
        plt.savefig(PNG_PATH, dpi=300)
        plt.show()

    def send_email_to(self, from_add, to_add, cc_add,
                      subject, html_text):
        '''
        :param from_add:发件人邮箱
        :param to_add:收件人邮箱
        :param cc_add:抄送人邮箱
        :param subject:邮件主题
        :param html_text:邮件主体xml
        :return:向收件人发送邮件
        '''

        str_from = self.__format_addr__(from_add)
        str_to = list()
        try:
            for a in to_add:
                str_to.append(self.__format_addr__(a))
        except Exception as e:
            str_to = to_add

        str_cc = list()
        try:
            for a in cc_add:
                str_cc.append(self.__format_addr__(a))
        except Exception as e:
            str_cc = cc_add

        msg_root = email.mime.multipart.MIMEMultipart('related')
        msg_root.preamble = 'This is a multi-part message in MIME format.'
        msg_alternative = email.mime.multipart.MIMEMultipart('alternative')
        msg_root.attach(msg_alternative)

        msg_text = email.mime.text.MIMEText(html_text, 'html', 'utf-8')
        msg_root['subject'] = Header(subject)
        msg_root['from'] = str_from
        msg_root['to'] = ','.join(str_to)
        msg_root['sc'] = ','.join(str_cc)
        msg_alternative.attach(msg_text)

        '''
        构造图片链接
        '''
        with open(PNG_PATH, 'rb') as file:
            send_image_file = file.read()
        image = email.mime.image.MIMEImage(send_image_file)
        image.add_header('Content-ID', '<image1>')
        disposition = 'attachment; filename=' + ''.join(PNG_FILE)
        image["Content-Disposition"] = disposition
        msg_root.attach(image)

        smtp = smtplib.SMTP(SMTP_SERVER)
        smtp.set_debuglevel(1)
        smtp.login(DOMAIN_NAME, DOMAIN_PWD)

        smtp.sendmail(from_add, to_add, msg_root.as_string())
        smtp.quit()

    def create_body(self):
        '''
        :return:构造邮件内容
        '''

        # 读取时间和tpmC信息到数组
        row = []
        with open(LOG_PATH, 'r') as file:
            row = file.readlines()
        p2_arm_list = []
        for line in row:
            line = list(line.strip().split(''))
            s = []
            for i in line:
                s.append(int(i))
            p2_arm_list.append(s)

        # 读取gaussdb版本信息到数组
        with open(LOG_GS_VERSION, 'r') as file:
            row = file.readlines()
        p2_version_list = []
        for line in row:
            line = list(line.strip().split(''))
            s = []
            for i in line:
                s.append(str(i))
            p2_version_list.append(s)

        # 填充日期信息、tpmC值、gaussdb版本信息
        with open(XML_FILE_FORMAT, 'r') as file:
            lines = file.readlines()
        with os.fdopen(os.open(XML_FILE, os.O_WRONLY | os.O_CREAT,
                               stat.S_IWUSR | stat.S_IRUSR), 'w+') as file:
            for s in lines:
                for i in range(0, 7):
                    for j in range(0, 4):
                        s = s.replace(
                            '[%s%s]' % (''.join(str(i)), ''.join(str(j))),
                            str(p2_arm_list[i][j]))
                        s = s.replace(
                            '[%s]' % (''.join(str(i))),
                            str(p2_version_list[i][0]))
                file.write(s)
            file.close()

        with open(XML_FILE, 'rb') as file:
            p2_arm_xml = file.read()

        return p2_arm_xml

if __name__ == '__main__':
    mail = Mail()

    thread1 = threading.Thread(target=mail.graph)
    thread1.setDaemon(True)
    thread1.start()
    thread1.join(2)

    body = mail.create_body()
    mail.send_email_to(SENDER, RECEIVER, CCTO, SUBJECT, body)

    pid = os.getpid()
    print(pid)
    os.kill(os.getpid(), signal.SIGTERM)
